package com.computer.spring.framework.aop.aspect;

import com.computer.spring.framework.aop.advice.BYAdvice;

import java.lang.reflect.Method;

/**
 * @Description
 * @Author MagicIce
 * @Date 2020/11/23 8:31
 */
public abstract class BYAbstractAspectJAdvice implements BYAdvice {

    private Method aspectMethod;
    private Object aspectTarget;

    public BYAbstractAspectJAdvice(Method aspectMethod, Object aspectTarget) {
        this.aspectMethod = aspectMethod;
        this.aspectTarget = aspectTarget;
    }

    /** 反射动态调用方法 */
    protected Object invokeAdviceMethod(BYJoinPoint joinPoint, Object returnValue, Throwable throwable) throws Throwable{
        Class<?>[] paramTypes = this.aspectMethod.getParameterTypes();
        if (null == paramTypes || paramTypes.length == 0){
            return this.aspectMethod.invoke(aspectTarget);
        }else {
            Object[] args = new Object[paramTypes.length];
            for (int i = 0; i < paramTypes.length; i++) {
                if (paramTypes[i] == BYJoinPoint.class){
                    args[i] = joinPoint;
                }else if (paramTypes[i] == Throwable.class){
                    args[i] = throwable;
                }else if ((paramTypes[i] == Object.class)){
                    args[i] = returnValue;
                }
            }
            return this.aspectMethod.invoke(aspectTarget, args);
        }
    }
}
